package com.iddaa.core.service.impl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collection;

import net.spy.memcached.MemcachedClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.iddaa.core.annotation.Memcached;
import com.iddaa.core.annotation.MemcachedRead;
import com.iddaa.core.dao.SeasonDAO;
import com.iddaa.core.domain.Season;
import com.iddaa.core.service.SeasonService;
import com.iddaa.core.service.SolrService;
import com.iddaa.core.util.Constants;

@Service("seasonService")
@Memcached(prefix = "Season", expiration = Constants.Cache.SEASON_EXPIRETIME)
public class SeasonServiceImpl implements SeasonService {

	@Autowired
	private SeasonDAO seasonDAO;

	@Autowired
	private SolrService solrService;

	@Override
	public void deleteSeason(Long id) {
		seasonDAO.delete(findById(id));
		solrService.updateSolr(id,"Season");
		deleteCache(id);
	}

	@Override
	@MemcachedRead
	public Season findById(Long id) {
		return seasonDAO.getById(id);

	}

	@Override
	public Collection<Season> loadAll() {
		return seasonDAO.loadAll();
	}

	@Override
	public void saveSeason(Season season) {
		seasonDAO.saveOrUpdate(season);
		solrService.updateSolr(season.getId(), season.getName(), "Season");
		evictCache(season);
	}

	@Async
	public void evictCache(Season season) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.set("Season:" + season.getId(), Constants.Cache.SEASON_EXPIRETIME, season);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Async
	public void deleteCache(Long id) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.delete("Season:" + id);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
